import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.stream.IntStream;

import javax.imageio.stream.FileImageOutputStream;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
import javax.swing.text.PlainDocument;

import com.ha.facecamera.configserver.ConfigServer;
import com.ha.facecamera.configserver.ConfigServerConfig;
import com.ha.facecamera.configserver.ConnectStateInvokeCondition;
import com.ha.facecamera.configserver.Constants;
import com.ha.facecamera.configserver.DataServer;
import com.ha.facecamera.configserver.DataServerConfig;
import com.ha.facecamera.configserver.pojo.AppConfig;
import com.ha.facecamera.configserver.pojo.AudiofreQuency;
import com.ha.facecamera.configserver.pojo.CaptureCompareData;
import com.ha.facecamera.configserver.pojo.EffectArea;
import com.ha.facecamera.configserver.pojo.EffectAreanew;
import com.ha.facecamera.configserver.pojo.Face;
import com.ha.facecamera.configserver.pojo.FacePage;
import com.ha.facecamera.configserver.pojo.Gateopening;
import com.ha.facecamera.configserver.pojo.ListFaceCriteria;
import com.ha.facecamera.configserver.pojo.ListSnapCriteria;
import com.ha.facecamera.configserver.pojo.NetConfig;
import com.ha.facecamera.configserver.pojo.Screenshot;
import com.ha.facecamera.configserver.pojo.Snap;
import com.ha.facecamera.configserver.pojo.SnapPage;
import com.ha.facecamera.configserver.pojo.Time;
import com.ha.facecamera.configserver.pojo.Transparent;
import com.ha.sdk.HaCamera;
import com.ha.tlv.Util;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class MainForm extends JFrame {
	
	private static final long serialVersionUID = -4081599548364704057L;
	
	private JPanel contentPane;
	private JTextField textField;
	private ConfigServer configServer;
	private DataServer dataServer;
	private JTextArea textArea;
	private JTextField textField_1;
	private DataViewDialog dataViewDialog;
    private SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private File twistDataDir;
	private boolean compactDataOut = false;
	private final static String[] strHex = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
         
	public static String getMD5One(byte[]  text) {
        StringBuffer sb = new StringBuffer();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] b = md.digest(text);
            for (int i = 0; i < b.length; i++) {
              int d = b[i];
               if (d < 0) {
                   d += 256;
               }
               int d1 = d / 16;
               int d2 = d % 16;
               sb.append(strHex[d1] + strHex[d2]);
           }
       } catch (NoSuchAlgorithmException e) {
           e.printStackTrace();
       }
       return sb.toString();
   }
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		
		EventQueue.invokeLater(() -> {
			try {
				MainForm frame = new MainForm();
				frame.setVisible(true);
			} catch (Exception e) {
				e.printStackTrace();
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public MainForm() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 1537, 766);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(new BorderLayout(0, 0));
		configServer = new ConfigServer();
		dataServer = new DataServer();
		
		JPanel panel = new JPanel();
		contentPane.add(panel, BorderLayout.NORTH);
		panel.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_1 = new JPanel();
		panel.add(panel_1, BorderLayout.NORTH);
		
		JLabel lblNewLabel = new JLabel("\u7AEF\u53E3\uFF1A");
		panel_1.add(lblNewLabel);
		
		textField = new JTextField();
		panel_1.add(textField);
		textField.setText("10001");
		textField.setColumns(10);
		
		JButton btnNewButton = new JButton("\u76D1\u542C");
		panel_1.add(btnNewButton);
		
		JButton btnNewButton_1 = new JButton("\u83B7\u53D6\u5E94\u7528\u53C2\u6570");
		btnNewButton_1.addActionListener((e) -> {
			String sn = JOptionPane.showInputDialog("通过sn获取");
			if(sn == null || sn.isEmpty()) return;
			AppConfig appConfig = configServer.getAppConfig(sn);
			if(appConfig == null) {
				textArea.append("获取sn为");
				textArea.append(sn);
				textArea.append("的应用参数失败！");
				textArea.append("\n");
				textArea.append("\t");
				textArea.append(configServer.getLastErrorMsg());
				textArea.append("\n");
			} else {
				textArea.append("获取sn为");
				textArea.append(sn);
				textArea.append("的应用参数成功！");
				textArea.append("\n");
				textArea.append("\t");
				textArea.append(appConfig.toJson());
				textArea.append("\n");
			}
		});
		
		JButton button_2 = new JButton("重启");
		button_2.addActionListener((e) -> {
			String sn = JOptionPane.showInputDialog("通过sn重启");
			if(sn == null || sn.isEmpty()) return;
			boolean ret = configServer.reboot(sn, 500);
			if(!ret) {
				textArea.append("重启sn为");
				textArea.append(sn);
				textArea.append("的设备失败！");
				textArea.append("\n");
				textArea.append("\t");
				textArea.append(configServer.getLastErrorMsg());
				textArea.append("\n");
			} else {
				textArea.append("重启sn为");
				textArea.append(sn);
				textArea.append("的设备成功！");
				textArea.append("\n");
			}
		});
		panel_1.add(button_2);
		panel_1.add(btnNewButton_1);
		
		JButton btnNewButton_2 = new JButton("\u83B7\u53D6\u8BBE\u5907\u65F6\u95F4");
		btnNewButton_2.addActionListener((e) -> {
			String sn = JOptionPane.showInputDialog("通过sn获取");
			if(sn == null || sn.isEmpty()) return;
			Time time = configServer.getTime(sn, 5000);
			if(time == null) {
				textArea.append("获取sn为");
				textArea.append(sn);
				textArea.append("的设备时间失败！");
				textArea.append("\n");
				textArea.append("\t");
				textArea.append(configServer.getLastErrorMsg());
				textArea.append("\n");
			} else {
				textArea.append("获取sn为");
				textArea.append(sn);
				textArea.append("的设备时间成功！");
				textArea.append("\n");
				textArea.append("\t");
				textArea.append(time.toJson());
				textArea.append("\n");
			}
		});
		panel_1.add(btnNewButton_2);
		
		JButton btnNewButton_3 = new JButton("\u8BBE\u7F6E\u8BBE\u5907\u65F6\u95F4");
		btnNewButton_3.addActionListener((e) -> {
			String sn = JOptionPane.showInputDialog("填入需要设置的设备sn");
			if(sn == null || sn.isEmpty()) return;
			String timeStr = JOptionPane.showInputDialog(MainForm.this, "填入需要设置的时间", new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()));
			if(timeStr == null || timeStr.isEmpty()) return;
			Time time = new Time();
			String[] timeStrs = timeStr.split(" ");
			time.setDate(timeStrs[0]);
			time.setTime(timeStrs[1]);
			if(!configServer.setTime(sn, time, 10000)) {
				textArea.append("设置sn为");
				textArea.append(sn);
				textArea.append("的设备时间失败！");
				textArea.append("\n");
				textArea.append("\t");
				textArea.append(configServer.getLastErrorMsg());
				textArea.append("\n");
			} else {
				textArea.append("设置sn为");
				textArea.append(sn);
				textArea.append("的设备时间成功！");
				textArea.append("\n");
				textArea.append("\t");
				textArea.append(time.toJson());
				textArea.append("\n");
			}
		});
		panel_1.add(btnNewButton_3);
		
		JButton btnNewButton_4 = new JButton("\u67E5\u524D20\u6761\u7279\u5F81\u503C");
		btnNewButton_4.addActionListener((e) -> {
			String sn = JOptionPane.showInputDialog("填入需要设置的设备sn");
			if(sn == null || sn.isEmpty()) return;
			FacePage pfp = configServer.listFace(sn, new ListFaceCriteria(), 15000);
			if(pfp == null) {
				textArea.append("获取sn为");
				textArea.append(sn);
				textArea.append("的前20条特征值失败！");
				textArea.append("\n");
				textArea.append("\t");
				textArea.append(configServer.getLastErrorMsg());
				textArea.append("\n");
			} else {
				textArea.append("获取sn为");
				textArea.append(sn);
				textArea.append("的前20条特征值成功！");
				textArea.append("\n");
				textArea.append("\t");
				textArea.append(pfp.toJson());
				textArea.append("\n");
			}
		});
		panel_1.add(btnNewButton_4);
		
		JButton btnNewButton_5 = new JButton("增加人脸");
		btnNewButton_5.addActionListener((e) -> {
			String sn = JOptionPane.showInputDialog("填入需要设置的设备sn");
			if(sn == null || sn.isEmpty()) return;
			AddFaceDialog afd = new AddFaceDialog();
			afd.setVisible(true);				
			Face face = afd.getFaceToUpload();
			if(face == null) return;
//			if(twistDataDir != null) {
//				if(new File(twistDataDir, face.getId() + ".twist").exists()) {
//					try {
//						face.setTwistImageData(new byte[][] {Files.readAllBytes(new File(twistDataDir, face.getId() + ".twist").toPath())});
//						face.setThumbImageData(new byte[][] {Files.readAllBytes(new File(twistDataDir, face.getId() + ".thumb").toPath())});
//					} catch (IOException e1) {
//						// TODO Auto-generated catch block
//						e1.printStackTrace();
//					}
//				}
//			}
			
			//System.out.println(configServer.deleteFace(sn, 3, 2000)+"清空");
			
			
			
			
			
			if(!configServer.addFace(sn, face, 5000)) {
				textArea.append("向sn为");
				textArea.append(sn);
				textArea.append("的设备添加人脸失败！");
				textArea.append("\n");
				textArea.append("\t");
				textArea.append(configServer.getLastErrorMsg()+","+configServer.getLastErrorCode());
				textArea.append("\n");
			} else {
				textArea.append("设置sn为");
				textArea.append(sn);
				textArea.append("的设备添加人脸成功！");
				textArea.append("\n");
				textArea.append("\t");
				textArea.append(face.toJson());
				textArea.append("\n");
			}
		});
		
		JButton button_1 = new JButton("设置参数");
		panel_1.add(button_1);
		button_1.addActionListener((e) -> {
			String sn = JOptionPane.showInputDialog("填入需要设置的设备sn");
			if(sn == null || sn.isEmpty()) return;
			AppConfig appConfig = configServer.getAppConfig(sn);
			if(appConfig == null) {
				textArea.append("获取sn为");
				textArea.append(sn);
				textArea.append("的应用参数失败！");
				textArea.append("\n");
				textArea.append("\t");
				textArea.append(configServer.getLastErrorMsg());
				textArea.append("\n");
			} else {
				ConfigDialog cd = new ConfigDialog(appConfig);
				cd.setVisible(true);
				boolean ret = configServer.setAppConfig(sn, appConfig, 5000);
				if(!ret){
					textArea.append("设置sn为");
					textArea.append(sn);
					textArea.append("的参数失败！");
					textArea.append("\n");
					textArea.append("\t");
					textArea.append(configServer.getLastErrorMsg());
					textArea.append("\n");
				} else {
					textArea.append("设置sn为");
					textArea.append(sn);
					textArea.append("的参数成功！");
					textArea.append("\n");
					textArea.append("\t");
					textArea.append(appConfig.toJson());
					textArea.append("\n");
				}
			}
		});
		// XXX
		panel_1.add(btnNewButton_5);
		
		JButton button_3 = new JButton("获取网络参数");
		panel_1.add(button_3);
		
		button_3.addActionListener((e) -> {
			String sn = JOptionPane.showInputDialog("通过sn获取");
			if(sn == null || sn.isEmpty()) return;
			NetConfig netConfig = configServer.getNetConfig(sn);
			if(netConfig == null) {
				textArea.append("获取sn为");
				textArea.append(sn);
				textArea.append("的网络参数失败！");
				textArea.append("\n");
				textArea.append("\t");
				textArea.append(configServer.getLastErrorMsg());
				textArea.append("\n");
			} else {
				textArea.append("获取sn为");
				textArea.append(sn);
				textArea.append("的网络参数成功！");
				textArea.append("\n");
				textArea.append("\t");
				textArea.append(netConfig.toJson());
				textArea.append("\n");
			}
		});
		
		JButton button_4 = new JButton("人脸校验√");
		button_4.addActionListener(e -> {
			if(button_4.getText().equals("人脸校验√")) {
				button_4.setText("人脸校验×");
				HaCamera.switchFaceCheckEnable(false);
			} else {
				button_4.setText("人脸校验√");
				HaCamera.switchFaceCheckEnable(true);
			}
		});
		
		JButton button_5 = new JButton("人员有效规则");
		button_5.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String sn = JOptionPane.showInputDialog("填入设备sn");
				if(sn == null || sn.isEmpty()) return;
				EffectArea[] effectAreas = configServer.getEffectAreas(sn, 5000);
				if(effectAreas == null) {
					textArea.append("获取sn为");
					textArea.append(sn);
					textArea.append("的有效规则失败！");
					textArea.append("\n");
					textArea.append("\t");
					textArea.append(configServer.getLastErrorMsg());
					textArea.append("\n");
					return;
				}
				SetEffectAreaDialog sead = new SetEffectAreaDialog();
				sead.setData(effectAreas);
				sead.setVisible(true);
				effectAreas = sead.getData();
				if(effectAreas != null) {
					boolean ret = configServer.setEffectAreas(sn, effectAreas, 5000);
					if(ret) {
						textArea.append("设置sn为");
						textArea.append(sn);
						textArea.append("的有效规则成功！");
						textArea.append("\n");
					} else {
						textArea.append("获取sn为");
						textArea.append(sn);
						textArea.append("的有效规则失败！");
						textArea.append("\n");
						textArea.append("\t");
						textArea.append(configServer.getLastErrorMsg());
						textArea.append("\n");
					}
				}
			}
		});
		panel_1.add(button_5);
		panel_1.add(button_4);
		
		JButton btnNewButton_6 = new JButton("打开门禁");
		btnNewButton_6.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String sn = JOptionPane.showInputDialog("填入设备sn");
				if(sn == null || sn.isEmpty()) return;
				
				GateopenDialog gt=new GateopenDialog();
				
				gt.getFrame().setVisible(true);
				Gateopening gatopen = gt.getGateopening();
				if(gatopen != null) {
					boolean ret = configServer.setGateopen(sn, gatopen, 5000);
					if(ret) {
						textArea.append("设置sn为");
						textArea.append(sn);
						textArea.append("的门禁成功！");
						textArea.append("\n");
					} else {
						textArea.append("获取sn为");
						textArea.append(sn);
						textArea.append("的门禁失败！");
						textArea.append("\n");
						textArea.append("\t");
						textArea.append(configServer.getLastErrorMsg());
						textArea.append("\n");
					}
				}
				
			}
		});
		panel_1.add(btnNewButton_6);
		
		JButton button_6 = new JButton("人员编号");
		button_6.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String sn = JOptionPane.showInputDialog("填入设备sn");
				if(sn == null || sn.isEmpty()) return;
				String[] per= configServer.getAllPersonID(sn, 5000);
				textArea.append("\n");
				for (String string : per) {
					
					textArea.append(string+",");
				}
				
				
				
			}
		});
		panel_1.add(button_6);
		
		JPanel panel_2 = new JPanel();
		panel.add(panel_2, BorderLayout.SOUTH);
		panel_2.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
		
		JButton btnNewButton_7 = new JButton("TF卡记录");
		btnNewButton_7.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String sn = JOptionPane.showInputDialog("填入设备sn");
				if(sn == null || sn.isEmpty()) return;
				ListSnapCriteria listsnap=new ListSnapCriteria();
				SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				
				try {
					listsnap.getRestrictions().SnaptimeBetween(sf.parse("2019-10-09 13:18:00"), sf.parse("2019-10-09 16:18:00"));
				} catch (ParseException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				SnapPage per= configServer.listSnap(sn, listsnap, 5000);
				textArea.append("\n");
				if(per.getTotal()>0) {
				for (Snap s1 : per.getSnap()) {
					textArea.append("\n");
					textArea.append(s1.toJson()+",");
				}
				}
			}
		});
		
		JButton btnNewButton_8 = new JButton("清空");
		btnNewButton_8.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				String sn = JOptionPane.showInputDialog("填入设备sn");
				if(sn == null || sn.isEmpty()) return;
				System.out.println(configServer.deleteFace(sn, 3, 5000)+"清空");
			}
		});
		
		JButton button_7 = new JButton("音频播放");
		button_7.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String sn = JOptionPane.showInputDialog("填入设备sn");
				if(sn == null || sn.isEmpty()) return;
				AudiofreQuency[] audi=  configServer.getaudiofrequency(sn, 30000);
				textArea.append("\n音频列表");
				if(audi!=null) {
					for (AudiofreQuency a : audi) {
						textArea.append(a.toJson()+",");
					}
					//播放音频
					if(audi.length>0) {
						configServer.setaudiofrequency(sn, audi[0], 3000);
						
					}
					
				}
				
				
				
			}
		});
		
		JButton btnNewButton_9 = new JButton("文字转语音播放");
		btnNewButton_9.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String sn = JOptionPane.showInputDialog("填入设备sn");
				if(sn == null || sn.isEmpty()) return;
				boolean re= configServer.setVoiceplayback(sn,"游方你好",3000);
				if(re) {
					textArea.append("\n播放成功");
				}else {
					
					textArea.append("\n播放失败"+configServer.getLastErrorMsg());
				}
				
			}
		});
		
		JButton button_8 = new JButton("查询人脸");
		button_8.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String sn = JOptionPane.showInputDialog("填入设备sn");
				if(sn == null || sn.isEmpty()) return;
				ListFaceCriteria cri=new ListFaceCriteria();
				cri.setIseffective(true);
				cri.getRestrictions().expireDateBetween(Constants.LONGLIVE, Constants.LONGLIVE);
				
				
				FacePage face=  configServer.listFace(sn, cri, 3000);
				 Face[] fac= face.getFaces();
				 for (Face face2 : fac) {
					 textArea.append("\n查询成功"+face2.getName()+","+face2.getCustom()+",伟根"+face2.getWiegandNo());
					System.out.println(face2.getName()+","+face2.getCustom());
//					face2.setCustom("自定义sss");
//					configServer.modifyFace(sn, face2, 3000);
				}
				 textArea.append("\n查询成功总数"+face.getTotal());
				System.out.println(face.getTotal());
				
			}
		});
		
		JButton btnNewButton_10 = new JButton("常闭");
		btnNewButton_10.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String sn = JOptionPane.showInputDialog("填入需要设置的设备sn");
				if(sn == null || sn.isEmpty()) return;
				AppConfig appConfig = configServer.getAppConfig(sn);//必须要先查询在修改，特别重要									
				appConfig.setRelaytype((byte)0);//0常闭 1常开
				appConfig.setRelay1((byte)1);//禁止继电器
				appConfig.setRelay2((byte)1);//禁止继电器
				
				if( configServer.setAppConfig(sn, appConfig, 3000)) {
					textArea.append("\n设置成功");
				}else {
					textArea.append("\n设置失败"+configServer.getLastErrorMsg());
					
				}
				
				
				
			}
		});
		
		JButton btnNewButton_11 = new JButton("打开继电器");
		btnNewButton_11.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				String sn = JOptionPane.showInputDialog("填入需要设置的设备sn");
				if(sn == null || sn.isEmpty()) return;
				AppConfig appConfig = configServer.getAppConfig(sn);//必须要先查询在修改，特别重要									
				appConfig.setRelaytype((byte)1);//0常闭 1常开  这里就是你的恢复正常，你正常是什么就填什么
				appConfig.setRelay1((byte)0);//打开继电器
				appConfig.setRelay2((byte)0);//打开继电器
				
				if( configServer.setAppConfig(sn, appConfig, 3000)) {
					textArea.append("\n设置成功");
				}else {
					textArea.append("\n设置失败"+configServer.getLastErrorMsg());
					
				}
				
			}
		});
		
		JButton button_9 = new JButton("常开");
		button_9.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String sn = JOptionPane.showInputDialog("填入需要设置的设备sn");
				if(sn == null || sn.isEmpty()) return;
				AppConfig appConfig = configServer.getAppConfig(sn);//必须要先查询在修改，特别重要									
				appConfig.setRelaytype((byte)1);//0常闭 1常开
				appConfig.setRelay1((byte)1);//禁止继电器
				appConfig.setRelay2((byte)1);//禁止继电器
				System.out.println(appConfig.getWorkMode());
				if( configServer.setAppConfig(sn, appConfig, 3000)) {
					textArea.append("\n设置成功");
				}else {
					textArea.append("\n设置失败"+configServer.getLastErrorMsg());
					
				}
				
				
			}
		});
		
		JButton button_10 = new JButton("截图");
		button_10.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String sn = JOptionPane.showInputDialog("填入需要设置的设备sn");
				if(sn == null || sn.isEmpty()) return;
				
				Screenshot scree=configServer.Getscreenshot(sn, 3000);
				if(scree!=null) {
				System.out.println(scree.getCaptureTime()+","+scree.getScreenshotimage().length);
				
				byte2image(scree.getScreenshotimage(),"E:/360Downloads/截图.jpg");
				textArea.append("\n截图成功");
				}else {
					
					textArea.append("\n截图失败"+configServer.getLastErrorMsg());
				}
				
				
			}
		});
		
		JButton btnNewButton_12 = new JButton("人员有效规则(15)");
		btnNewButton_12.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String sn = JOptionPane.showInputDialog("填入需要设置的设备sn");
				if(sn == null || sn.isEmpty()) return;
				//-------------------获取时间调度规则---------------------------
				JSONObject reqjson=new JSONObject();
				reqjson.put("version", "0.2");//版本
				reqjson.put("cmd", "request schedule params");//命令
				
				EffectAreanew effn=  configServer.getHttpJson(sn, reqjson.toString(), 3000);
				if(effn!=null) {
					
					System.out.println(effn.getRulejson());
					textArea.append("\n获取时间调度成功"+effn.getRulejson());
					
				}
				
				
				//--------------------------设置时间调度规则(格式看http协议文档这里写了按天的格式)-----------------------------------
				
				JSONObject setjson=new JSONObject();
				setjson.put("version", "0.2");
				setjson.put("cmd", "update schedule params");//命令
				JSONArray kinds=new JSONArray();//多分类调度表。取值范围：0~15
				JSONObject kind=new JSONObject();
				kind.put("name", "测试");//类别名称
				kind.put("kind", 1);//类别代码1-15
				kind.put("mode", "daily");//调度模式。daily：按天调度。weekly：按周调度
				
				JSONArray days=new JSONArray();//各天时间段  调度模式如果是按天，就一组数据     如果按周则7组数据周一到周日
				JSONObject day=new JSONObject();
				JSONArray sections=new JSONArray();//单天时间段
				
				JSONObject section=new JSONObject();
				
				section.put("start", "{hour:"+8+",minute:"+10+"}");//起始时间点。闭区间（包含该时间）。
				section.put("end", "{hour:"+18+",minute:"+10+"}");//结束时间点。开区间（不包含该时间）。
				sections.add(section);
				day.put("sections", sections);
				days.add(day);
				
				
				kind.put("days", days);
				
				kinds.add(kind);
				setjson.put("kinds", kinds);
				System.out.println(setjson);
				EffectAreanew eff=new EffectAreanew();
				eff.setRulejson(setjson.toString());
			
				boolean bl=  configServer.sethttpjson(sn, eff, 3000);
				
				if(bl) {
					
					textArea.append("\n设置时间调度成功");
					
				}else {
					
					textArea.append("\n设置时间调度失败"+configServer.getLastErrorMsg());
					
				}
				
				
				
				
			}
		});
		
		JButton btnNewButton_13 = new JButton("透明串口");
		btnNewButton_13.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				String sn = JOptionPane.showInputDialog("填入需要设置的设备sn");
				if(sn == null || sn.isEmpty()) return;
				Transparent tran=new Transparent();
				tran.setNo(1);
				tran.setText("efghip");
				
				boolean ret=configServer.setTransparent(sn,tran,3000);
				if(ret) {
				
				textArea.append("\n设置成功");
				}else {
					
					textArea.append("\n截图失败"+configServer.getLastErrorMsg());
				}
				
				
			}
			
			
			
			
		});
		
		JButton button_11 = new JButton("替换屏保");
		button_11.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String sn = JOptionPane.showInputDialog("填入需要设置的设备sn");
				if(sn == null || sn.isEmpty()) return;
				
				
				
			}
		});
		
		JButton btnNewButton_14 = new JButton("体温校正");
		btnNewButton_14.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				String sn = JOptionPane.showInputDialog("填入需要设置的设备sn");
				if(sn == null || sn.isEmpty()) return;
				AppConfig appConfig = configServer.getAppConfigreal(sn);//必须要先查询在修改，特别重要									
				appConfig.setTemp_corre(6.6f);
				
				if( configServer.setAppConfig(sn, appConfig, 3000)) {
					textArea.append("\n设置成功");
				}else {
					textArea.append("\n设置失败"+configServer.getLastErrorMsg());
					
				}
			}
		});
		panel_2.add(btnNewButton_14);
		panel_2.add(button_11);
		panel_2.add(btnNewButton_13);
		panel_2.add(btnNewButton_12);
		panel_2.add(button_10);
		panel_2.add(button_9);
		panel_2.add(btnNewButton_11);
		panel_2.add(btnNewButton_10);
		panel_2.add(button_8);
		panel_2.add(btnNewButton_9);
		panel_2.add(button_7);
		panel_2.add(btnNewButton_8);
		panel_2.add(btnNewButton_7);
		
		JLabel label = new JLabel("端口：");
		panel_2.add(label);
		
		textField_1 = new JTextField();
		panel_2.add(textField_1);
		textField_1.setText("10002");
		textField_1.setColumns(10);
		
		JButton button = new JButton("监听");
		button.addActionListener((e) -> {
			DataServerConfig dsc = new DataServerConfig();
//			if(JOptionPane.showConfirmDialog(MainForm.this, "是否启用加密链路，需要jks证书") == JOptionPane.OK_OPTION) {
//				JFileChooser jfc = new JFileChooser();
//				jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
//				jfc.setMultiSelectionEnabled(false);
//				jfc.showDialog(this, "选择加密证书");
//				dsc.jksFilePath = jfc.getSelectedFile().getAbsolutePath();
//				dsc.jksPassword = JOptionPane.showInputDialog("输入密码：");
//			}
			dsc.connectStateInvokeCondition = ConnectStateInvokeCondition.SnKnown;
			if(JOptionPane.showConfirmDialog(MainForm.this, "是否简化数据输出？") == JOptionPane.OK_OPTION) {
				compactDataOut = true;
			}
			boolean ret = dataServer.start(Integer.parseInt(textField_1.getText()), dsc);
			if(ret) {
				textArea.append("启动数据服务器成功！");
				textArea.append("\n");
				dataViewDialog.setVisible(true);
				dataServer.onCameraConnected((val) -> {
					try {
						EventQueue.invokeAndWait(() -> {
							textArea.append("设备已连接-数据端口 ");
							textArea.append(val);
							textArea.append("\n");
						});
					} catch (InvocationTargetException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (InterruptedException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				});
				dataServer.onCameraDisconnected((val) -> {
					try {
						EventQueue.invokeAndWait(() -> {
							textArea.append("设备已断开-数据端口 ");
							textArea.append(val);
							textArea.append("\n");
						});
					} catch (InvocationTargetException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (InterruptedException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				});
				dataServer.onCaptureCompareDataReceived((data) -> {
					
//					try {
//						
//						//System.out.println(data.getFaceRegionInEnvironment().width+"dfsa");
//						//System.out.println(data.getFaceRegionInFeature().height);
//						//System.out.println(data.toJson().substring(0, 200));
//						System.out.println(data.getSn()+"序列号");
//						//Thread.sleep(15000);
//	    			Files.write(new File(getpath(data.getCameraID())+"/"+"initdata.txt").toPath(), ("抓拍时间:"+sf.format(data.getCaptureTime())).getBytes(), StandardOpenOption.APPEND, StandardOpenOption.CREATE);
//					Files.write(new File(getpath(data.getCameraID())+"/"+"initdata.txt").toPath(), ("\tsequenceID:"+data.getSequenceID()).getBytes(), StandardOpenOption.APPEND, StandardOpenOption.CREATE);
//					Files.write(new File(getpath(data.getCameraID())+"/"+"initdata.txt").toPath(), ("\tmatchScore:"+data.getMatchScore()).getBytes(), StandardOpenOption.APPEND, StandardOpenOption.CREATE);
//					//Files.write(new File(getpath(data.getCameraID())+"/"+"initdata.txt").toPath(), ("\tlen:"+data.getFeatureImageData().length).getBytes(), StandardOpenOption.APPEND, StandardOpenOption.CREATE);
//					Files.write(new File(getpath(data.getCameraID())+"/"+"initdata.txt").toPath(), System.lineSeparator().getBytes(), StandardOpenOption.APPEND, StandardOpenOption.CREATE);
					//byte2image(data.getFeatureImageData(),getpath(data.getCameraID()+"/image/")+data.getSequenceID()+".jpg");
//					} catch (Exception e1) {
//						// TODO Auto-generated catch block
//						e1.printStackTrace();
//					}
					
					
					
					try {
						EventQueue.invokeAndWait(() -> {
//							System.out.println("fdsaf");
//							System.out.println(data.getFaceRegionInEnvironment().width+"dfsa");
							textArea.append("收到抓拍对比数据\n\t");
							System.out.println("比对类型"+data.getMath_type()+"是否实时"+data.isRealtime()+"自定义字段"+data.getCustom()+"伟根"+data.getWiegandNo1()+"二维码类型"+data.getCodetype()+"二维码"+data.getCodetext()+",体温"+data.getTemperature()+",口罩"+data.getIsMask());
							if(!compactDataOut)
								textArea.append(data.toJson());
							else {
								CaptureCompareData data_ = (CaptureCompareData) data.clone();
								data_.setEnvironmentImageData(null);
								data_.setFeatureData(null);
								data_.setFeatureImageData(null);
								data_.setModelImageData(null);
								data_.setVideoData(null);
								textArea.append(data_.toJson());
							}
							textArea.append("\n");
							dataViewDialog.showCaptureData(data);
						});
					} catch (InvocationTargetException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				});
				dataServer.onAuthing((time, username, password) -> {
					// XXX 如果要校验用户名密码，请使用如下代码
					//return username.equals("xiaohe") && Util.judgeRegPassword(time, "123456", password);
					System.out.println(String.format("dataServer 收到鉴权消息username=>%s password=>%s", username, new String(password)));
					return true;
				});
			}
		});
		panel_2.add(button);
		btnNewButton.addActionListener((e) -> {
			ConfigServerConfig csc = new ConfigServerConfig();
//				if(JOptionPane.showConfirmDialog(MainForm.this, "是否启用加密链路，需要jks证书") == JOptionPane.OK_OPTION) {
//					JFileChooser jfc = new JFileChooser();
//					jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
//					jfc.setMultiSelectionEnabled(false);
//					jfc.showDialog(this, "选择加密证书");
//					csc.jksFilePath = jfc.getSelectedFile().getAbsolutePath();
//					csc.jksPassword = JOptionPane.showInputDialog("输入密码：");
//				}
				//csc.connectStateInvokeCondition=ConnectStateInvokeCondition.DevicenoOrSnKnown;
//				if(JOptionPane.showConfirmDialog(MainForm.this, "是否启用无人脸模式？（启动监听会崩溃的选是）") == JOptionPane.OK_OPTION) {
//					csc.noNativeMode = true;
//					JFileChooser jfc = new JFileChooser();
//					jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
//					jfc.setMultiSelectionEnabled(false);
//					jfc.showDialog(this, "选择已预处理的人员图片文件夹");
//					twistDataDir = jfc.getSelectedFile();
//				}
				//csc.connectStateInvokeCondition = com.ha.facecamera.configserver.ConnectStateInvokeCondition.DeviceNoKnown;
			    
				boolean ret = configServer.start(Integer.parseInt(textField.getText()), csc);
				
				if(ret) {
					textArea.append("启动配置服务器成功！");
					textArea.append("\n");
					configServer.onCameraConnected((val) -> {
						 
						try {
							EventQueue.invokeAndWait(() -> {
								textArea.append("设备已连接-配置端口 ");
								Time t=  configServer.getTimeBySn(val,10000);
								
								
								textArea.append(val);
								textArea.append("\n\tAppConfig:\n\t\t");
								textArea.append(configServer.getAppConfig(val).toJson());
								textArea.append("\n\tVersion:\n\t\t");
								textArea.append(configServer.getVersion(val).toJson());
								textArea.append("\ntime"+t);
							});
						} catch (InvocationTargetException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						} catch (InterruptedException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					});
					configServer.onCameraDisconnected((val) -> {
						try {
							EventQueue.invokeAndWait(() -> {
								textArea.append("设备已断开-配置端口 ");
								textArea.append(val);
								textArea.append("\n\tAppConfig:\n\t\t");
								//textArea.append(configServer.getAppConfig(val).toJson());
								textArea.append("\n\tVersion:\n\t\t");
								textArea.append(configServer.getVersion(val).toJson());
								textArea.append("\n");
							});
						} catch (InvocationTargetException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						} catch (InterruptedException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					});
					configServer.onAuthing((time, username, password) -> {
						// XXX 如果要校验用户名密码，请使用如下代码
						//return username.equals("xiaohe") && Util.judgeRegPassword(time, "123456", password);
						System.out.println(String.format("configServer 收到鉴权消息username=>%s password=>%s", username, Util.judgeRegPassword(time, "password", password)));
						return true;
					});
					
					configServer.onQrcode((text,sn)->{
						
						System.out.println("二维码内容："+text+",sn"+sn);
						return true;
					});
					
					configServer.onTransparent((text,sn)->{
						System.out.println("透明串口内容"+text);
						
					});
					
					
				}
		});
		
		JScrollPane scrollPane = new JScrollPane();
		contentPane.add(scrollPane, BorderLayout.CENTER);
		
		textArea = new JTextArea();
		textArea.setDocument(new LimitativeDocument(textArea, 50));
		scrollPane.setRowHeaderView(textArea);

		dataViewDialog = new DataViewDialog(this);
		dataViewDialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
	}
    private String getpath(String path){
    	String paths="";
    	try {
    		paths=new File("").getCanonicalPath()+"/log/"+path;
			 File file =new File(paths);
			 

   	    
   		if(!file.exists()){  
   		    file.mkdirs();  
   		}
			
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return paths;
    }
    
    
    
    public void byte2image(byte[] data,String path){
	    
	    try{
	    	if(data.length<3||path.equals("")) return;	
	    	
	    FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
	    imageOutput.write(data, 0, data.length);
	    imageOutput.close();
	    System.out.println("Make Picture success,Please find image in " + path);
	    } catch(Exception ex) {
	      System.out.println("Exception: " + ex);
	     // ex.printStackTrace();
	    }
	  }

	
	void addFaceFromCaptureData(String sn1, byte[] featureImageData) {
		String sn = JOptionPane.showInputDialog("填入需要设置的设备sn", sn1);
		if(sn == null || sn.isEmpty()) return;
		AddFaceDialog afd = new AddFaceDialog(featureImageData);
		afd.setVisible(true);
		Face face = afd.getFaceToUpload();
		if(face == null) return;
		if(!configServer.addFace(sn, face, 5000)) {
			textArea.append("向sn为");
			textArea.append(sn);
			textArea.append("的设备添加人脸失败！");
			textArea.append("\n");
			textArea.append("\t");
			textArea.append(configServer.getLastErrorMsg());
			textArea.append("\n");
		} else {
			textArea.append("设置sn为");
			textArea.append(sn);
			textArea.append("的设备添加人脸成功！");
			textArea.append("\n");
			textArea.append("\t");
			textArea.append(face.toJson());
			textArea.append("\n");
		}
	}

	public class LimitativeDocument extends PlainDocument{
		private static final long serialVersionUID = -5038185503502384746L;
		private JTextComponent textComponent;
	    private int lineMax = 10;
	    public   LimitativeDocument(JTextComponent tc,int lineMax){     
	        textComponent = tc;
	        this.lineMax = lineMax;
	    }
	    public   LimitativeDocument(JTextComponent tc){     
	        textComponent = tc;
	    }
	    public void insertString(int offset, String s, AttributeSet attributeSet) throws BadLocationException {
	        
	        String value =   textComponent.getText();
	        long lineCount = IntStream.range(0,value.length()).parallel().filter(c -> value.charAt(c) == '\n').count();
	        if(lineCount >= lineMax) {
	        	int removeStartIdx = 0;
	        	long removeDoneLineCount = lineCount;
	        	while(true) {
	        		if(value.charAt(removeStartIdx++) == '\n' && --removeDoneLineCount < lineMax) {
	        			break;
	        		}
	        	}
	        	offset -= removeStartIdx;
	        	super.remove(0, removeStartIdx);
	        }
	        super.insertString(offset, s, attributeSet);
	    }
	}
}
